//
//  GCMLoginViewController.m
//  GeeCityManager
//
//  Created by 聚城科技 on 16/3/8.
//  Copyright © 2016年 聚城科技. All rights reserved.
//

#import "GCMLoginViewController.h"
#import "GCMMainViewController.h"
#import "GCMURLViewController.h"
#import "ADView.h"
#import "XRQJpush.h"
#import "GCMMain1ViewController.h"

@interface GCMLoginViewController ()<UIAlertViewDelegate>

@end

@implementation GCMLoginViewController{
    
    UIView *_bgView ;
    UITextField *_userName ;
    UITextField *_passWord ;
    NSString *_str ;
    NSMutableDictionary *_userInfo ;
}

//视图将要出现
- (void)viewWillAppear:(BOOL)animated{

    self.navigationController.navigationBarHidden = YES;
}
//视图加载
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //    判断是否进入引导页
    if ([self isFirstStartApp]) {
        
        NSUserDefaults *s = [NSUserDefaults standardUserDefaults];
        [s setObject:@"http://0.89892528.cn:8700/" forKey:@"URL"];
//        [self guide];
        [self forward];
        
    }else{
    
        [self forward];
       
        //写完待修改
//        GCMMainViewController *main =[[GCMMainViewController alloc]init];
//        [self.navigationController pushViewController:main animated:YES];
//        UIBarButtonItem *backItem = [[UIBarButtonItem alloc] init];
//        backItem.title = @"主页";
//        self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
//        self.navigationItem.backBarButtonItem = backItem;
    }
}
-(void)forward{
    //设置提示框背景色

    [[LPPopup appearance] setPopupColor:[UIColor whiteColor]];
    [self initData];
    [self createUI];

}
-(void)guide{
    NSArray *guideArray = @[@"start_s3.jpg"];
    
    ADView *ad = [[ADView alloc]initWithFrame:self.view.bounds];
    ad.imageArray = guideArray;
    ad.tag = 876;
    __weak typeof(self) weakSelf = self;
    void(^block)(void) = ^{
        ADView  *ad = (ADView *)[self.view viewWithTag:876];
        [ad removeSub];
        [ad removeFromSuperview];
        [weakSelf forward];
    };
    ad.block = block;
    [ad reloadData];
    [self.view addSubview:ad];
}
//是否是第一次登陆
-(BOOL)isFirstStartApp{
    NSUserDefaults *s = [NSUserDefaults standardUserDefaults];
    
    //读取的是 上一次用户第几次启动程序
    NSNumber *tag = [s objectForKey:@"tag"];
    if (tag.intValue >= 1) {
        //用户启动过程序
        //写入新的值（获取旧的tag值,加1后写入磁盘）
        int i = tag.intValue;
        i++;
        [s setObject:[NSNumber numberWithInt:i] forKey:@"tag"];
        [s synchronize];
        return NO;
        
    }else{
        //用户第一次启动程序
        [s setObject:[NSNumber numberWithInt:1] forKey:@"tag"];
        [s synchronize];//一定要同步到磁盘
        return YES;
    }
}

-(void)initData{

    _userInfo = [[NSMutableDictionary alloc]init];
}

-(void)createUI{

//    常见背景图
    UIImageView *bgImageView  = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    bgImageView.image = [UIImage imageNamed:@"login_background1.png"];
    bgImageView.userInteractionEnabled = YES;
    //    增加长按手势
    UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPressGesture:)];
    [bgImageView addGestureRecognizer:longPressGesture];
    [self.view addSubview:bgImageView];
//
    _bgView = [[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT-250, SCREEN_WIDTH, 250)];
    _bgView.backgroundColor = [UIColor clearColor];
    _bgView.userInteractionEnabled = YES;
    [self.view addSubview:_bgView];
    
    
    UIImageView *nameInputImageView  = [[UIImageView alloc]initWithFrame:CGRectMake(40, 0, SCREEN_WIDTH - 80, 40)];
    nameInputImageView.image = [UIImage imageNamed:@"login_bg_input"];
    nameInputImageView.userInteractionEnabled = YES;
    [_bgView addSubview:nameInputImageView];
    //用户名
    _userName =[[UITextField alloc]initWithFrame:CGRectMake(10, 0, SCREEN_WIDTH-100, 40)];
    _userName.placeholder=@"请输入账号";
    _userName.layer.cornerRadius =10;
    _userName.layer.borderColor =[UIColor blackColor].CGColor;
    _userName.backgroundColor =[UIColor whiteColor];
    _userName.clearButtonMode = UITextFieldViewModeAlways;
    _userName.tag = 1;
    _userName.delegate=self;
    [nameInputImageView addSubview:_userName];
    
    UIImageView *passWordInputImageView  = [[UIImageView alloc]initWithFrame:CGRectMake(40, 60, SCREEN_WIDTH - 80, 40)];
    passWordInputImageView.image = [UIImage imageNamed:@"login_bg_input"];
    passWordInputImageView.userInteractionEnabled = YES;
    [_bgView addSubview:passWordInputImageView];
    //密码
    _passWord =[[UITextField alloc]initWithFrame:CGRectMake(10, 0, SCREEN_WIDTH-100, 40)];
    _passWord.placeholder=@"请输入密码";
    _passWord.layer.cornerRadius =10;
    _passWord.secureTextEntry = YES;
    _passWord.layer.borderColor =[UIColor blackColor].CGColor;
    _passWord.backgroundColor =[UIColor whiteColor];
    _passWord.clearButtonMode = UITextFieldViewModeAlways;
    _passWord.tag = 2;
    _passWord.delegate =self;
    [passWordInputImageView addSubview:_passWord];
//  登陆按钮
    UIButton * logbutton =[[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2-60, 120, 120, 50)];
    
  //  [logbutton setImage:[UIImage imageNamed:@"login_btn_login"] forState:UIControlStateNormal];
    [logbutton setBackgroundImage:[UIImage imageNamed:@"login_btn"] forState:UIControlStateNormal];
    logbutton.tag = 9999;
    [logbutton addTarget:self action:@selector(logButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [_bgView addSubview:logbutton];
    
    
    //取出缓存
//    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
//    NSArray *arr2 = [user arrayForKey:@"arr"];
//    
//    
//    for (NSString *str in arr2) {
//        if (str == nil) {
//            return ;
//        }else{
//            
//            _userName.text = arr2[0];
//            _passWord.text =arr2[1];
//        }
//    }
//    if (arr2 != nil) {
//        [self logButtonClick];
//    }

}

- (void) timeEnough

{
    
    UIButton *btn=(UIButton*)[self.view viewWithTag:9999];
    
    btn.selected=NO;
    
}

-(void)logButtonClick{
    
    UIButton *btn=(UIButton*)[self.view viewWithTag:9999];
    
    if(btn.selected) return;
    
    btn.selected=YES;
    
    [self performSelector:@selector(timeEnough) withObject:nil afterDelay:3.0];
    
    if (![_userName.text isEqualToString:@""]&&![_passWord.text isEqualToString:@""]) {
    
    [GCMLoginHttpRequst postUserInfoWithUserName:_userName.text AndPassWord:_passWord.text Success:^(id userInfo, NSError *err) {
        NSLog(@"++++%@",userInfo);
        _userInfo = userInfo;
/**
 
 {
 code = 0;
 data =     {
 areaId = 1;
 auth = 0;
 departId = 42;
 id = 185;
 realName = "\U8bbe\U5907\U4e3b\U7ba1";
 };
 message = success;
 success = 1;
 }
 
 */
        
        if ([_userInfo[@"success"] integerValue] == 1)
        {
            
            
            //        创建缓存
            NSUserDefaults *User = [NSUserDefaults standardUserDefaults];
            NSArray *arr = @[_userName.text,_passWord.text];
            //NSLog(@"====1==%@",arr);
            [User setValue:arr forKey:@"arr"];
            
            [XRQJpush setBieming:arr[0]];
            
//            存数据
            NSMutableDictionary *infoDic  = [[NSMutableDictionary alloc]init];
                infoDic  = [_userInfo valueForKey:@"data"];
//            把数据缓存起来供使用
            [[NSUserDefaults standardUserDefaults]setObject:infoDic forKey:@"userInfo"];
//            NSLog(@"=========%@",_userInfo);
            [GCMUserInfo instance].areaId = [infoDic valueForKey:@"areaId"];
            [GCMUserInfo instance].auth = [infoDic valueForKey:@"auth"];
            [GCMUserInfo instance].departId = [infoDic valueForKey:@"departId"];
            [GCMUserInfo instance].uid = [infoDic valueForKey:@"id"];
            [GCMUserInfo instance].position = [infoDic valueForKey:@"position"];
            [GCMUserInfo instance].realName = [infoDic valueForKey:@"realName"];
            [GCMUserInfo instance].pic = [infoDic valueForKey:@"pic"];
            [GCMUserInfo instance].copyright = [infoDic valueForKey:@"copyright"];
            [GCMUserInfo instance].oaServer = [infoDic valueForKey:@"oaServer"];
            [GCMUserInfo instance].glc = [infoDic valueForKey:@"glc"];
            [GCMUserInfo instance].company = [infoDic valueForKey:@"company"];
            
            //            登陆成功就进行统计
            [GCMMainHttpRequst ClickTimes:@"登陆" Success:^(id times, NSError *err) {
                NSLog(@"测试统计登陆次数成功");
                NSLog(@"%@",times);
            }];
            //       一会把跳转写到这
            NSUserDefaults *s = [NSUserDefaults standardUserDefaults];
            NSString *styleStr = [s valueForKey:@"style"];
            if ([styleStr isEqualToString:@"Window风格"]) {
                GCMMainViewController *main =[[GCMMainViewController alloc]init];
                UIWindow *window = [UIApplication sharedApplication].keyWindow;
                UINavigationController *navc = [[UINavigationController alloc]initWithRootViewController:main];
                window.rootViewController = navc;
                
                
            }else{
                GCMMain1ViewController *main =[[GCMMain1ViewController alloc]init];
                UIWindow *window = [UIApplication sharedApplication].keyWindow;
                UINavigationController *navc = [[UINavigationController alloc]initWithRootViewController:main];
                window.rootViewController = navc;
            }
            
//            GCMMain1ViewController *main =[[GCMMain1ViewController alloc]init];
//            
//            UIWindow *window = [UIApplication sharedApplication].keyWindow;
//            UINavigationController *navc = [[UINavigationController alloc]initWithRootViewController:main];
//            window.rootViewController = navc;
            


//            [self.navigationController pushViewController:main animated:YES];
            UIBarButtonItem *backItem = [[UIBarButtonItem alloc] init];
            backItem.title = @"主页";
            self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
            self.navigationItem.backBarButtonItem = backItem;
            
        }
        //登录失败
        else
        {
            if (_userInfo[@"message"]) {
                UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"错误提示" message:_userInfo[@"message"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alter show];
                
            }else{
//                NSLog(@"%@",_userInfo);
                UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"请输入正确的URL" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alter show];
                
            }
        }
        

    }];
       }else{
    
        LPPopup *popup = [LPPopup popupWithText:@"用户名或密码不能为空"];
        
        [popup showInView:self.view
            centerAtPoint:self.view.center
                 duration:kLPPopupDefaultWaitDuration
               completion:nil];
    }
    
}



//处理长按事件
- (void)handleLongPressGesture:(UILongPressGestureRecognizer *)longPressGesture{
    if (longPressGesture.state == UIGestureRecognizerStateBegan) {
        
        GCMURLViewController *urlVC = [[GCMURLViewController alloc]init];
        [self.navigationController pushViewController:urlVC animated:YES];
        UIBarButtonItem *backItem = [[UIBarButtonItem alloc] init];
        backItem.title = @"系统设置";
        self.navigationController.navigationBar.tintColor = [UIColor blueColor];
        self.navigationItem.backBarButtonItem = backItem;
        return;
        
    }
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
